package com.hexiang.interceptor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

@Slf4j
public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        log.info(String.format("Sending request %s on %s%n,header=%s,body=%s",
                request.url(), chain.connection(), request.headers(), request.body() != null ? request.body().toString() : ""));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        log.info(String.format("Received response for %s in %.1fms%n ,header=%s,response=%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers(), response));
        return response;
    }
}